<?php

// 超时订单
namespace app\queue;

use app\model\admin\CzOrder;
use app\model\mini\Order;
use app\model\mini\OrderLog;
use think\facade\Db;

class CloseOrder
{
    protected $order_id;
    protected $failMaxNum = 3;  //失败最大次数将删除队列
    protected $czOrderModel;


    public function fire($job, $data)
    {
        if (!$this->checkJob($data)) {
            // 检查不通过
            $job->delete();
            return;
        }
        if ($job->attempts() > 100) {
            $job->delete();
            return false;
        }
        if ($this->doJob($data)) {
            // 执行成功
            $job->delete();
        } else if ($job->attempts() > $this->failMaxNum) {
            //通过这个方法可以检查这个任务已经重试了几次了
            $job->delete();
        }
    }
    public function doJob($data)
    {
        storage_log("执行队列 order_id" . $data['order_id']);
        $this->order_id = $data['order_id'];
        $this->czOrderModel = Order::find($data['order_id']);
        // 
        if ($this->czOrderModel->pay_status != 0) {
            // 标记队列完成,支付的跳过
            // storage_log("pay_status!=1");
            return true;
        }
        // todo 订单状态判断
        // if (in_array($this->czOrderModel->order_status, [3, 4])) {
        //     // 标记完成，不处理
        //     // storage_log("order_status 3 4");
        //     return true;
        // }

        // 修改为超时
        Db::table('user_order')->where('id', $this->czOrderModel->id)->update([
            "pay_status" => 3,
            "remark" => '超时未支付',
            "act_remark" => '队列修改为超时',
            "updated_at" => time()
        ]);
        // 添加订单日志
        OrderLog::create([
            "order_id" => $this->czOrderModel->id,
            "message" => "超时未支付"
        ]);
        return true;
    }
    public function checkJob($data)
    {
        return true;
    }
}
